package com.sdkj.fixed.asset.assets.controller;

import com.sdkj.fixed.asset.api.assets.BorrowApi;
import com.sdkj.fixed.asset.api.assets.in_vo.BorrowIssueExtend;
import com.sdkj.fixed.asset.api.assets.in_vo.Params;
import com.sdkj.fixed.asset.api.assets.in_vo.SelPrams;
import com.sdkj.fixed.asset.api.assets.in_vo.SignatureParam;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseHistoryResult;
import com.sdkj.fixed.asset.assets.service.BorowService;
import com.sdkj.fixed.asset.assets.util.ExcelStyle;
import com.sdkj.fixed.asset.common.base.BaseResultVo;
import com.sdkj.fixed.asset.common.base.PageBean;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.pojo.assets.BorrowIssue;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author niuliwei
 * @description 资产借用与归还
 * @date 2020/7/23 16:24
 */
@Controller
public class BorrowController implements BorrowApi {
    @Autowired
    private BorowService service;
    @Autowired
    private HttpServletResponse response;

    @Override
    public BaseResultVo add(BorrowIssueExtend param) {
        service.add(param);
        return BaseResultVo.success(param);
    }

    @Override
    public BaseResultVo getAllPage(PageParams<SelPrams> param) {
        List<BorrowIssueExtend> list = service.getAllPage(param);
        PageBean pageBean = new PageBean(list);
        return BaseResultVo.success(pageBean);
    }

    @Override
    public BaseResultVo selById(Params param) {
        BorrowIssueExtend resultVo = service.selById(param.getId());
        return BaseResultVo.success(resultVo);
    }

    @Override
    public BaseResultVo udpById(BorrowIssueExtend param) {
        service.udpById(param);
        return BaseResultVo.success();
    }

    @Override
    public BaseResultVo backById(BorrowIssue issue) {
        service.backById(issue);
        return BaseResultVo.success();
    }

    @Override
    public BaseResultVo delById(Params param) {
        service.delById(param.getId());
        return BaseResultVo.success();
    }

    @Override
    public BaseResultVo updState(SignatureParam param) {
        service.updState(param);
        return BaseResultVo.success();
    }

    @Override
    public void print(String ids) throws Exception {
        List<BorrowIssueExtend> extendss = service.print(ids);
        String fileName = "资产借用单";
        HSSFWorkbook wb = new HSSFWorkbook();
        extendss.stream().forEach(extend ->{
            String title = "资产借用单";
            String sheetName = extend.getNumber();

            HSSFRow row = null;
            HSSFCell cell = null;
            int rownum = 0;
            // 建立新的sheet对象（excel的表单） 并设置sheet名字
            HSSFSheet sheet = wb.createSheet(sheetName);
            sheet.setDefaultColumnWidth(18);
            sheet.setColumnWidth(0, 256 * 6);
            sheet.setDefaultRowHeight((short) 512);

            // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
            row = sheet.createRow(rownum++);
            row.setHeight((short) 1000 );
            // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
            cell = row.createCell(1);
            // 合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));
            cell.setCellValue(title);
            cell.setCellStyle(ExcelStyle.styleTitle(wb));

            String[] row1 = {"借用单号：", extend.getNumber(), "", "借用日期：",extend.getLendDate(), "", "借用人：", extend.getBorrowUser()};
            String[] row2 = {"借用备注：", extend.getNote(), "归还日期：", extend.getActualBackDate()};
            String[] row3 = {"资产明细："};
            String[] row4 = {"序号","资产条码","资产类别","资产名称","规格型号","SN号","金额","管理员"};

            List<String[]> rowList = new ArrayList<>();
            rowList.add(row1);
            rowList.add(row2);
            rowList.add(row3);
            rowList.add(row4);

            for (String[] rows : rowList) {
                row = sheet.createRow(rownum++);
                for (int i = 0; i < rows.length; i++) {
                    cell = row.createCell(i + 1);
                    cell.setCellValue(rows[i]);
                    if(rownum == 4){
                        cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 3));
                        row.setHeight((short)700);
                    } else if (rownum == 5){
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));
                    } else {
                        cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 2));
                    }

                }
            }

            //合并单元格
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 8));

            //遍历数据
            int j = 1;
            for (WarehouseHistoryResult result : extend.getResults()) {
                row = sheet.createRow(rownum++);
                String[] cells = {"", result.getAssetCode(), result.getAssetClassName(), result.getAssetName(), result.getSpecificationModel(), result.getSnNumber(), result.getAmount(), result.getAdmin()};
                for (int i = 0; i < cells.length; i++) {
                    cell = row.createCell(i + 1);
                    if(i==0){
                        cell.setCellValue(j++);
                    } else {
                        cell.setCellValue(cells[i]);
                    }
                    cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                }
            }

            String[] lastRow = {"借用人签字：", "", "", "", "", "", "签字时间：", ""};
            row = sheet.createRow(rownum++); // 创建最后一行
            row.setHeight((short) 700);
            for (int i = 0; i < lastRow.length; i++) {
                cell = row.createCell(i + 1);
                cell.setCellValue(lastRow[i]);
                cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 2));
            }
        });


        // 输出Excel文件
        OutputStream output = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition","attachment; filename="+ URLEncoder.encode(fileName + ".xlsx", "UTF-8"));    //filename =  文件名
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
    }

}
